/**
 * 多模型对比测试页面
 * 简化版本，用于快速测试多模型对比功能
 */

import React, { useState } from 'react';
import { Card, Button, Input, Select, Space, Alert, Spin } from 'antd';
import { PlayCircleOutlined } from '@ant-design/icons';
import { ModelComparison } from '../components/multi-model/ModelComparison';
import { simpleMultiModelService, SimpleComparisonResult } from '../services/simple-multi-model.service';

const { TextArea } = Input;
const { Option } = Select;

export const TestMultiModelPage: React.FC = () => {
  const [prompt, setPrompt] = useState('请解释什么是人工智能，并举例说明其在日常生活中的应用。');
  const [selectedModels, setSelectedModels] = useState<string[]>(['GPT-4', 'Claude-3-Sonnet']);
  const [loading, setLoading] = useState(false);
  const [results, setResults] = useState<SimpleComparisonResult[]>([]);

  const handleQuickTest = async () => {
    if (!prompt.trim() || selectedModels.length === 0) {
      return;
    }

    setLoading(true);
    setResults([]);

    try {
      const comparisonResults = await simpleMultiModelService.compareModels(
        prompt,
        selectedModels,
        3
      );
      setResults(comparisonResults);
    } catch (error) {
      console.error('Quick test failed:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleComparisonComplete = (results: SimpleComparisonResult[]) => {
    console.log('Comparison completed:', results);
  };

  return (
    <div style={{ padding: '24px', maxWidth: '1200px', margin: '0 auto' }}>
      <h1>多模型对比功能测试</h1>
      
      <Alert
        message="功能说明"
        description="这是一个简化的多模型对比测试页面。您可以输入提示词，选择要对比的模型，然后查看不同模型的回复结果。"
        type="info"
        showIcon
        style={{ marginBottom: 24 }}
      />

      {/* 快速测试区域 */}
      <Card title="快速测试" style={{ marginBottom: 24 }}>
        <Space direction="vertical" style={{ width: '100%' }} size="middle">
          <div>
            <label><strong>测试提示词：</strong></label>
            <TextArea
              rows={3}
              value={prompt}
              onChange={(e) => setPrompt(e.target.value)}
              placeholder="输入您想要测试的提示词..."
              style={{ marginTop: 8 }}
            />
          </div>

          <div>
            <label><strong>选择模型：</strong></label>
            <Select
              mode="multiple"
              style={{ width: '100%', marginTop: 8 }}
              placeholder="选择要对比的模型"
              value={selectedModels}
              onChange={setSelectedModels}
            >
              {simpleMultiModelService.getAvailableModels().map(model => (
                <Option key={model} value={model}>
                  {model}
                </Option>
              ))}
            </Select>
          </div>

          <div style={{ textAlign: 'center' }}>
            <Button
              type="primary"
              icon={<PlayCircleOutlined />}
              onClick={handleQuickTest}
              loading={loading}
              disabled={!prompt.trim() || selectedModels.length === 0}
              size="large"
            >
              开始快速测试
            </Button>
          </div>
        </Space>
      </Card>

      {/* 测试结果 */}
      {loading && (
        <Card style={{ textAlign: 'center', marginBottom: 24 }}>
          <Spin size="large" />
          <p style={{ marginTop: 16 }}>正在调用 {selectedModels.length} 个模型进行对比...</p>
        </Card>
      )}

      {results.length > 0 && (
        <Card title="快速测试结果" style={{ marginBottom: 24 }}>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(400px, 1fr))', gap: '16px' }}>
            {results.map((result, index) => (
              <Card
                key={result.modelName}
                title={result.modelName}
                size="small"
                extra={
                  <Space>
                    <span>{result.duration}ms</span>
                    <span>${result.cost}</span>
                  </Space>
                }
              >
                {result.error ? (
                  <Alert message="生成失败" description={result.error} type="error" />
                ) : (
                  <div style={{ 
                    maxHeight: '300px', 
                    overflow: 'auto', 
                    whiteSpace: 'pre-wrap',
                    fontSize: '14px',
                    lineHeight: '1.6'
                  }}>
                    {result.content}
                  </div>
                )}
              </Card>
            ))}
          </div>

          {/* 统计信息 */}
          <div style={{ marginTop: 16, padding: '16px', backgroundColor: '#f5f5f5', borderRadius: '8px' }}>
            <h4>对比统计</h4>
            {(() => {
              const stats = simpleMultiModelService.getModelStats(results);
              return (
                <Space size="large">
                  <span>成功率: {stats.successRate}%</span>
                  <span>平均响应时间: {stats.averageResponseTime}ms</span>
                  <span>总成本: ${stats.totalCost}</span>
                  <span>最快模型: {stats.fastestModel}</span>
                </Space>
              );
            })()}
          </div>
        </Card>
      )}

      {/* 完整的多模型对比组件 */}
      <ModelComparison onCompare={handleComparisonComplete} />
    </div>
  );
};
